﻿#include "ribbontoolbar.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QToolButton>
#include <QFontDatabase>
#include <QDebug>
#include <QColorDialog>
#include <QPainter>
#include <QWidgetAction>
#include <QApplication>
#include <QTabBar>  
#include <QSpinBox>
#include <QLabel>
#include <QPainterPath>

const int RIBBON_HEIGHT = 110; 
const int BUTTON_SIZE = 36;    
const int ICON_SIZE = 20;      
const int TAB_HEIGHT = 30;     

RibbonToolbar::RibbonToolbar(QWidget* parent)
	: QWidget(parent),
	m_tabWidget(new QTabWidget(this)),
	m_boldBtn(nullptr),
	m_italicBtn(nullptr),
	m_underlineBtn(nullptr),
	m_fontCombo(nullptr),
	m_sizeCombo(nullptr),
	m_insertImageBtn(nullptr),
	m_insertTableBtn(nullptr),
	m_fontColorBtn(nullptr),
	m_colorMenu(nullptr),
	m_currentColor(Qt::black) 
{
	setStyleSheet(R"(
		/* ================ 根容器：Ribbon 整体变白 ================ */
		 QWidget#RibbonToolbar {
			 background-color: white; /* 最外层容器全白 */
		 }

		/* ================ 覆盖所有子控件背景 ================ */
		QTabWidget, QTabBar, QToolBar, QWidget {
			 background-color: white; /* 强制所有子控件继承白色 */
		 }
		QPushButton {
            border: none; /* 彻底去掉所有边框 */
            background-color: transparent; /* 透明背景 */
            padding: 8px 12px; /* 增大点击区域，避免文字紧贴边缘 */
        }

        /* ================ 鼠标悬停效果（WPS风格浅灰） ================ */
		QPushButton:hover {
			background-color: #F2F2F2; /* 浅灰色背景 */
			border-radius: 4px; /* 圆角让hover更柔和 */
		}
		QToolButton:checked {
			 color: #333333; /* 文字保持深灰，与未选中状态协调 */
			 background-color: #E0E0E0; /* 选中时的灰色背景，和 QPushButton:checked 保持一致 */
				border-radius: 4px; /* 保持圆角效果 */
		}
        /* ================ 鼠标按下效果（加深颜色） ================ */
        QPushButton:pressed {
            background-color: #E6E6E6; /* 比hover更深的灰色 */
        }
        
        /* ================ 选中状态（更深的灰色） ================ */
        QPushButton:checked {
            color: #333333; /* 文字保持深灰，与未选中状态协调 */
            background-color: #E0E0E0; /* 比按下状态更深的灰色（核心修改） */
            border-radius: 4px; /* 保持与hover状态一致的圆角 */
        }

        /* 【核心】QTabWidget 整体样式（Tab 居中 + 大尺寸） */
        QTabWidget {
            font-family: "Microsoft YaHei", sans-serif;
            font-size: 12pt;
            background-color: #F7F7F7; /* WPS 浅灰背景 */
            border: none; /* 去掉默认边框 */
        }

        /* Tab 栏居中 + 下划线选中态 */
        QTabBar {
            alignment: center; /* 标签页居中对齐（关键！） */
            font-size: 13pt;
            height: )" + QString::number(TAB_HEIGHT) + QStringLiteral("px;") + R"(
            background-color: white;  /* Tab 栏背景 */
            border-bottom: 1px solid #ECECEC; /* 底部分割线 */
        }

        QTabBar::tab {
            padding: 8px 24px; /* 增大 Tab 间距 */
            margin: 0 4px;     /* 按钮之间留白 */
            color: #333333;    /* 文字颜色 */
            border: none;      /* 去掉默认边框 */
            border-bottom: 2px solid transparent; /* 选中下划线预备 */
        }

        QTabBar::tab:selected {
            color: #0078D7;    /* WPS 选中文字蓝 */
            border-bottom: 2px solid #0078D7; /* 下划线高亮 */
        }

        /* 【大尺寸按钮】QToolBar + QToolButton 样式 */
        QToolBar {
            border: none; 
            spacing: 12px; /* 按钮之间大间距 */
            margin: 8px;   /* 与 Tab 栏留白 */
			background-color: white; 
        }

        QToolButton {
            width: )" + QString::number(BUTTON_SIZE) + QStringLiteral("px;") + R"(
            height: )" + QString::number(BUTTON_SIZE) + QStringLiteral("px;") + R"(
            font-size: 12pt;
            color: #333333;
            border: none; 
            border-radius: 4px;
            background-color: transparent;
            toolButtonStyle: Qt::ToolButtonTextUnderIcon; /* 图标在上，文字在下 */
            iconSize: )" + QString::number(ICON_SIZE) + QStringLiteral("px;") + R"(
        }

        QToolButton:hover {
            background-color: #F2F2F2; /* WPS hover 浅蓝 */
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 悬浮阴影 */
        }

        QToolButton:pressed {
            background-color: #E6E6E6; /* 按压更深的蓝色 */
        }
		
        /* 【字体选择框】贴近 WPS 样式 */
        QComboBox {
            height: 36px;
            font-size: 12pt;
            padding: 0 12px;
            border: 1px solid #DCDCDC;
            border-radius: 4px;
            background-color: #FFFFFF;
        }

        QComboBox::drop-down {
            border-left: 1px solid #DCDCDC;
        }
    )");

	QVBoxLayout* mainLayout = new QVBoxLayout(this);
	mainLayout->setContentsMargins(0, 0, 0, 0);
	mainLayout->setSpacing(0);
	mainLayout->addWidget(m_tabWidget);

	createHomeTab();
	createInsertTab();
	//createViewTab();

	// 初始化字体列表
	initFontLists();
	buildColorMenu();
	buildColorMenu();
}

void RibbonToolbar::createHomeTab()
{
	QWidget* homeTab = new QWidget();
	QVBoxLayout* layout = new QVBoxLayout(homeTab);
	layout->setContentsMargins(2, 2, 2, 2);
	layout->setSpacing(0);

	QToolBar* fontToolBar = createToolBar("Font");
	layout->addWidget(fontToolBar);

	m_openBtn = new QPushButton(this);
	m_openBtn->setToolTip(tr("open"));
	m_openBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_openBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_openBtn->setIcon(QIcon(":/icon/open.svg"));
	fontToolBar->addWidget(m_openBtn);
	connect(m_openBtn, &QPushButton::clicked, this, [=]() {emit  openRequested(); });

	m_newBtn = new QPushButton(this);
	m_newBtn->setToolTip(tr("new"));
	m_newBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_newBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_newBtn->setIcon(QIcon(":/icon/new.svg"));
	fontToolBar->addWidget(m_newBtn);
	connect(m_newBtn, &QPushButton::clicked, this, [=]() {emit  newRequested(); });

	m_saveBtn = new QPushButton(this);
	m_saveBtn->setToolTip(tr("save"));
	m_saveBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_saveBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_saveBtn->setIcon(QIcon(":/icon/save.svg"));
	fontToolBar->addWidget(m_saveBtn);
	connect(m_saveBtn, &QPushButton::clicked, this, [=]() {emit  saveRequested(); });

	m_undoBtn = new QPushButton(this);
	m_undoBtn->setToolTip(tr("undo"));
	m_undoBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_undoBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_undoBtn->setIcon(QIcon(":/icon/undo.svg"));
	fontToolBar->addWidget(m_undoBtn);
	connect(m_undoBtn, &QPushButton::clicked, this, [=]() {emit  undoRequested(); });

	m_redoBtn = new QPushButton(this);
	m_redoBtn->setToolTip(tr("redo"));
	m_redoBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_redoBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_redoBtn->setIcon(QIcon(":/icon/redo.svg"));
	fontToolBar->addWidget(m_redoBtn);
	connect(m_redoBtn, &QPushButton::clicked, this, [=]() {emit  redoRequested(); });

	QFrame* separator2 = new QFrame();
	separator2->setFrameShape(QFrame::VLine);
	separator2->setFrameShadow(QFrame::Sunken);
	separator2->setStyleSheet("background-color: #ECECEC;");
	fontToolBar->addWidget(separator2);

	m_boldBtn = new QPushButton(this);
	m_boldBtn->setCheckable(true);
	m_boldBtn->setToolTip(tr("Bold"));
	m_boldBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_boldBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_boldBtn->setIcon(QIcon(":/icon/bold.svg"));
	fontToolBar->addWidget(m_boldBtn);

	m_italicBtn = new QPushButton(this);
	m_italicBtn->setCheckable(true);
	m_italicBtn->setToolTip(tr("Italic"));
	m_italicBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_italicBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_italicBtn->setIcon(QIcon(":/icon/italic.svg"));
	fontToolBar->addWidget(m_italicBtn);

	m_underlineBtn = new QPushButton(this);
	m_underlineBtn->setCheckable(true);
	m_underlineBtn->setToolTip(tr("Underline"));
	m_underlineBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_underlineBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_underlineBtn->setIcon(QIcon(":/icon/underline.svg"));
	fontToolBar->addWidget(m_underlineBtn);

	m_strikethroughBtn = new QPushButton(this);
	m_strikethroughBtn->setCheckable(true);
	m_strikethroughBtn->setToolTip(tr("Strikethrough"));
	m_strikethroughBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_strikethroughBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_strikethroughBtn->setIcon(QIcon(":/icon/strike.svg"));
	fontToolBar->addWidget(m_strikethroughBtn);

	QFrame* separator = new QFrame();
	separator->setFrameShape(QFrame::VLine);
	separator->setFrameShadow(QFrame::Sunken);
	separator->setStyleSheet("background-color: #ECECEC;");
	fontToolBar->addWidget(separator);

	m_fontCombo = new QComboBox(this);
	m_fontCombo->setToolTip(tr("Font Family"));
	m_fontCombo->setFixedWidth(120);
	fontToolBar->addWidget(m_fontCombo);

	m_sizeCombo = new QComboBox(this);
	m_sizeCombo->setToolTip(tr("Font Size"));
	m_sizeCombo->setMinimumWidth(40);
	m_sizeCombo->setFixedWidth(60);
	fontToolBar->addWidget(m_sizeCombo);

	fontToolBar->addSeparator();

	m_fontDecreaseBtn = new QPushButton(this);
	m_fontDecreaseBtn->setToolTip(tr("Decrease Font Size"));
	m_fontDecreaseBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_fontDecreaseBtn->setIcon(QIcon(":/icon/fontdec.svg"));
	m_fontDecreaseBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	fontToolBar->addWidget(m_fontDecreaseBtn);

	m_fontIncreaseBtn = new QPushButton(this);
	m_fontIncreaseBtn->setToolTip(tr("Increase Font Size"));
	m_fontIncreaseBtn->setFixedSize(BUTTON_SIZE, BUTTON_SIZE);
	m_fontIncreaseBtn->setIconSize(QSize(ICON_SIZE, ICON_SIZE));
	m_fontIncreaseBtn->setIcon(QIcon(":/icon/fontinc.svg"));
	fontToolBar->addWidget(m_fontIncreaseBtn);

	QFrame* separator1 = new QFrame();
	separator1->setFrameShape(QFrame::VLine);
	separator1->setFrameShadow(QFrame::Sunken);
	separator1->setStyleSheet("background-color: #ECECEC;");
	fontToolBar->addWidget(separator1);

	m_fontColorBtn = new QToolButton(this);
	m_fontColorBtn->setToolTip(tr("Font color"));
	m_fontColorBtn->setIcon(createUnderlineIcon(Qt::black, ICON_SIZE));
	m_fontColorBtn->setIconSize(QSize(ICON_SIZE * 2, ICON_SIZE * 2));
	m_fontColorBtn->setFixedSize(BUTTON_SIZE * 2, BUTTON_SIZE);  
	m_fontColorBtn->setMenu(m_colorMenu);
	m_fontColorBtn->setPopupMode(QToolButton::MenuButtonPopup);
	fontToolBar->addWidget(m_fontColorBtn);
	createHighlightControls(fontToolBar);
	createParagraphButtons(fontToolBar);

	m_styleCombo = new QComboBox(this);
	m_styleCombo->setToolTip(tr("样式选择"));
	m_styleCombo->setFixedWidth(160);
	m_styleCombo->addItems(QStringList() << tr("title1") << tr("title2") << tr("title3") << tr("normal")<<tr("bold")<<tr("code")<<tr("quote"));
	fontToolBar->addWidget(m_styleCombo);

	connect(m_boldBtn, &QPushButton::clicked, this, &RibbonToolbar::onBoldClicked);
	connect(m_italicBtn, &QPushButton::clicked, this, &RibbonToolbar::onItalicClicked);
	connect(m_underlineBtn, &QPushButton::clicked, this, &RibbonToolbar::onUnderlineClicked);
	connect(m_strikethroughBtn, &QPushButton::clicked, this, &RibbonToolbar::onStrikethroughClicked);
	connect(m_fontCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &RibbonToolbar::onFontFamilyChanged);
	connect(m_sizeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &RibbonToolbar::onFontSizeChanged);
	connect(m_fontDecreaseBtn, &QPushButton::clicked, this, &RibbonToolbar::onFontSizeDecrease);
	connect(m_fontIncreaseBtn, &QPushButton::clicked, this, &RibbonToolbar::onFontSizeIncrease);
	connect(m_fontColorBtn, &QToolButton::clicked, this, &RibbonToolbar::showColorPanel);
	connect(m_styleCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index) {
		QString styleName = m_styleCombo->itemText(index);
		emit styleSelected(styleName); 
	});
	m_tabWidget->addTab(homeTab, tr("Start"));
}

void RibbonToolbar::createInsertTab()
{
	QWidget* insertTab = new QWidget();
	QVBoxLayout* layout = new QVBoxLayout(insertTab);
	layout->setContentsMargins(2, 2, 2, 2);
	layout->setSpacing(0);

	QToolBar* insertToolBar = createToolBar("insert");
	layout->addWidget(insertToolBar);

	m_insertImageBtn = new QPushButton(tr("Image"), this);
	m_insertImageBtn->setToolTip(tr("Insert image"));
	m_insertImageBtn->setText(tr("image"));
	m_insertImageBtn->setFixedSize(80, 40);
	m_insertImageBtn->setIcon(QIcon(":/icon/image.svg"));
	connect(m_insertImageBtn, &QPushButton::clicked, this, &RibbonToolbar::onInsertImageClicked);
	insertToolBar->addWidget(m_insertImageBtn);

	m_insertTableBtn = new QPushButton(tr("Table"), this);
	m_insertTableBtn->setToolTip(tr("Insert table"));
	m_insertTableBtn->setFixedSize(80, 40);
	m_insertTableBtn->setText(tr("table"));
	m_insertTableBtn->setIcon(QIcon(":/icon/table.svg"));
	insertToolBar->addWidget(m_insertTableBtn);
	connect(m_insertTableBtn, &QPushButton::clicked, this, &RibbonToolbar::onInsertTableClicked);

	m_shapeBtn = new QToolButton(this); 
	m_shapeBtn->setText(tr("Shape"));
	m_shapeBtn->setToolTip(tr("Insert shapes"));
	m_shapeBtn->setFixedSize(80, 40);
	m_shapeBtn->setIcon(QIcon(":/icon/shape.svg")); 
	m_shapeBtn->setPopupMode(QToolButton::MenuButtonPopup); 

	QMenu* shapeMenu = new QMenu(m_shapeBtn);

	QAction* rectAction = new QAction(tr("Rectangle"), this);
	rectAction->setData("rectangle");
	connect(rectAction, &QAction::triggered, this, [this]() {
		emit shapeSelected("rectangle");
		});

	QAction* circleAction = new QAction(tr("Circle"), this);
	circleAction->setData("circle");
	connect(circleAction, &QAction::triggered, this, [this]() {
		emit shapeSelected("circle");
		});

	QAction* lineAction = new QAction(tr("Line"), this);
	lineAction->setData("line");
	connect(lineAction, &QAction::triggered, this, [this]() {
		emit shapeSelected("line");
		});

	shapeMenu->addAction(rectAction);
	shapeMenu->addAction(circleAction);
	shapeMenu->addAction(lineAction);

	m_shapeBtn->setMenu(shapeMenu);

	insertToolBar->addWidget(m_shapeBtn);

	m_tabWidget->addTab(insertTab, tr("Insert"));
}

void RibbonToolbar::createViewTab()
{
	QWidget* viewTab = new QWidget();
	QVBoxLayout* layout = new QVBoxLayout(viewTab);
	layout->setContentsMargins(2, 2, 2, 2);
	layout->setSpacing(0);

	QToolBar* viewToolBar = createToolBar("view");
	layout->addWidget(viewToolBar);

	QPushButton* zoomInBtn = new QPushButton(tr("Zoom In"), this);
	zoomInBtn->setFixedSize(80, 30);
	viewToolBar->addWidget(zoomInBtn);

	QPushButton* zoomOutBtn = new QPushButton(tr("Zoom Out"), this);
	zoomOutBtn->setFixedSize(80, 30);
	viewToolBar->addWidget(zoomOutBtn);

	m_tabWidget->addTab(viewTab, tr("view"));
}

QToolBar* RibbonToolbar::createToolBar(const QString& title)
{
	QToolBar* toolBar = new QToolBar(title, this);
	toolBar->setMovable(false);
	toolBar->setFloatable(false);
	toolBar->setIconSize(QSize(24, 24));
	toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
	toolBar->setStyleSheet("QToolBar { border: none; }");
	return toolBar;
}

void RibbonToolbar::createParagraphButtons(QToolBar* toolBar)
{
	m_alignLeftBtn = new QToolButton(toolBar);
	m_alignLeftBtn->setIcon(QIcon(":/icon/alignleft.svg"));
	m_alignLeftBtn->setToolTip(tr("Left aligned"));
	m_alignLeftBtn->setCheckable(true);

	m_alignCenterBtn = new QToolButton(toolBar);
	m_alignCenterBtn->setIcon(QIcon(":/icon/aligncenter.svg"));
	m_alignCenterBtn->setToolTip(tr("Center align"));
	m_alignCenterBtn->setCheckable(true);

	m_alignRightBtn = new QToolButton(toolBar);
	m_alignRightBtn->setIcon(QIcon(":/icon/alignright.svg"));
	m_alignRightBtn->setToolTip(tr("Right aligned"));
	m_alignRightBtn->setCheckable(true);

	m_alignJustifyBtn = new QToolButton(toolBar);
	m_alignJustifyBtn->setIcon(QIcon(":/icon/alignjustify.svg"));
	m_alignJustifyBtn->setToolTip(tr("Justify"));
	m_alignJustifyBtn->setCheckable(true);

	m_alignDistributedBtn = new QToolButton(toolBar);
	m_alignDistributedBtn->setIcon(QIcon(":/icon/aligndistributed.svg")); 
	m_alignDistributedBtn->setToolTip(tr("Distributed alignment"));
	m_alignDistributedBtn->setCheckable(true); 

	auto connectAlignmentButton = [this](QToolButton* btn)
	{
		connect(btn, &QToolButton::clicked, this, [this, btn]() 
			{
			// 取消所有按钮选中状态
			m_alignLeftBtn->setChecked(false);
			m_alignCenterBtn->setChecked(false);
			m_alignRightBtn->setChecked(false);
			m_alignJustifyBtn->setChecked(false);
			m_alignDistributedBtn->setChecked(false);
			// 选中当前点击的按钮
			btn->setChecked(true);

			// 发射对应的对齐信号
			Qt::Alignment align = Qt::AlignLeft;
			if (btn == m_alignLeftBtn) 
				align = Qt::AlignLeft;
			else if (btn == m_alignCenterBtn) 
				align = Qt::AlignCenter;
			else if (btn == m_alignRightBtn) 
				align = Qt::AlignRight;
			else if (btn == m_alignJustifyBtn) 
				align = Qt::AlignJustify;
			else if (btn == m_alignDistributedBtn)
				align = Qt::AlignJustify | Qt::AlignAbsolute; 
			emit alignmentChanged(align);
			});
	};

	connectAlignmentButton(m_alignLeftBtn);
	connectAlignmentButton(m_alignCenterBtn);
	connectAlignmentButton(m_alignRightBtn);
	connectAlignmentButton(m_alignJustifyBtn);
	connectAlignmentButton(m_alignDistributedBtn);

	m_alignLeftBtn->setChecked(true);

	auto connectBtn = [this](QToolButton* btn)
	{
		connect(btn, &QToolButton::clicked, this, [this, btn]()
			{
				m_alignLeftBtn->setChecked(m_alignLeftBtn == btn);
				m_alignCenterBtn->setChecked(m_alignCenterBtn == btn);
				m_alignRightBtn->setChecked(m_alignRightBtn == btn);
				m_alignJustifyBtn->setChecked(m_alignJustifyBtn == btn);
				m_alignDistributedBtn->setChecked(m_alignDistributedBtn == btn);
				Qt::Alignment align = Qt::AlignLeft;
				if (m_alignLeftBtn->isChecked())      align = Qt::AlignLeft;
				else if (m_alignCenterBtn->isChecked()) align = Qt::AlignCenter;
				else if (m_alignRightBtn->isChecked())  align = Qt::AlignRight;
				else if (m_alignJustifyBtn->isChecked())align = Qt::AlignJustify;
				else if (m_alignDistributedBtn->isChecked()) align = Qt::AlignJustify | Qt::AlignAbsolute;
				emit alignmentChanged(align);
			});
	};
	connectBtn(m_alignLeftBtn);
	connectBtn(m_alignCenterBtn);
	connectBtn(m_alignRightBtn);
	connectBtn(m_alignJustifyBtn);
	connectBtn(m_alignDistributedBtn);
	toolBar->addWidget(m_alignLeftBtn);
	toolBar->addWidget(m_alignCenterBtn);
	toolBar->addWidget(m_alignRightBtn);
	toolBar->addWidget(m_alignJustifyBtn);
	toolBar->addWidget(m_alignDistributedBtn);

	QFrame* separator = new QFrame();
	separator->setFrameShape(QFrame::VLine);
	separator->setFrameShadow(QFrame::Sunken);
	separator->setStyleSheet("background-color: #ECECEC;");
	toolBar->addWidget(separator);
}

void RibbonToolbar::initFontLists()
{
	QFontDatabase database;
	foreach(const QString & family, database.families()) 
	{
		m_fontCombo->addItem(family);
	}

	m_standardSizes = { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 };
	foreach(int size, m_standardSizes)
	{
		m_sizeCombo->addItem(QString::number(size));
	}

	m_fontCombo->setCurrentText("Arial");
	m_sizeCombo->setCurrentText("12");
	m_currentFontSize = 12;
}

void RibbonToolbar::buildColorMenu()
{
	m_colorMenu = new QMenu(this);

	QVector<QColor> colors =
	{
		Qt::black, Qt::white, Qt::red, Qt::green, Qt::blue,
		Qt::cyan, Qt::magenta, Qt::yellow, Qt::gray, Qt::darkRed,
		Qt::darkGreen, Qt::darkBlue, Qt::darkCyan, Qt::darkMagenta, Qt::darkYellow
	};

	QWidget* colorPanel = new QWidget();
	QGridLayout* gridLayout = new QGridLayout(colorPanel);
	gridLayout->setSpacing(2); 
	gridLayout->setContentsMargins(4, 4, 4, 4);

	int row = 0, col = 0;
	for (const QColor& color : colors)
	{
		QToolButton* colorBtn = new QToolButton(colorPanel);
		colorBtn->setFixedSize(24, 24); 
		colorBtn->setStyleSheet("QToolButton { border: 1px solid #ccc; }");
		colorBtn->setIcon(createUnderlineIcon(color,40)); 
		colorBtn->setIconSize(QSize(40, 40));

		connect(colorBtn, &QToolButton::clicked, this, [this, color]()
			{
			onColorSelected(color);
			});

		gridLayout->addWidget(colorBtn, row, col);
		col++;
		if (col >= 5) 
		{
			col = 0;
			row++;
		}
	}
	QWidgetAction* widgetAction = new QWidgetAction(m_colorMenu);
	widgetAction->setDefaultWidget(colorPanel);
	m_colorMenu->addAction(widgetAction);
}

QPixmap RibbonToolbar::createUnderlineIcon(const QColor& color, int size)
{
	QPixmap pixmap(size, size);
	pixmap.fill(Qt::transparent);

	QPainter painter(&pixmap);
	painter.setRenderHint(QPainter::Antialiasing, true);
	painter.setRenderHint(QPainter::TextAntialiasing, true);
	painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

	const QString systemFont = QApplication::font().family(); 
	QFont font(systemFont.isEmpty() ? "Arial" : systemFont, 9, QFont::Bold);
	font.setPixelSize(size * 0.6); 
	painter.setFont(font);

	QFontMetrics fm = painter.fontMetrics();
	const int textWidth = fm.horizontalAdvance("A");
	const int textAscent = fm.ascent();
	const int textDescent = fm.descent();

	const int textY = (size - textAscent) / 2 + textAscent;
	const int underlineY = textY + textDescent + size * 0.1;

	const int textX = (size - textWidth) / 2;
	const int underlineX1 = size * 0.1;
	const int underlineX2 = size - size * 0.1;

	painter.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap));
	painter.drawText(textX, textY, "A");

	QPen underlinePen(color, size * 0.05);
	underlinePen.setCapStyle(Qt::RoundCap);
	painter.setPen(underlinePen);
	painter.drawLine(underlineX1, underlineY, underlineX2, underlineY);

	return pixmap;
}

void RibbonToolbar::showColorPanel()
{
	m_colorMenu->popup(m_fontColorBtn->mapToGlobal(QPoint(0, m_fontColorBtn->height())));
}

void RibbonToolbar::setBoldState(bool bold) 
{
	if (m_boldBtn && m_boldBtn->isChecked() != bold)
	{
		m_boldBtn->setChecked(bold);
		m_bold = bold;
	}
}

void RibbonToolbar::setItalicState(bool italic) 
{
	if (m_italicBtn && m_italicBtn->isChecked() != italic) 
	{
		m_italicBtn->setChecked(italic);
		m_italic = italic;
	}
}

void RibbonToolbar::setUnderlineState(bool underline) 
{
	if (m_underlineBtn && m_underlineBtn->isChecked() != underline) 
	{
		m_underlineBtn->setChecked(underline);
		m_underline = underline;
	}
}

void RibbonToolbar::setFontFamily(const QString& family) 
{
	if (m_fontCombo && m_fontCombo->currentText() != family)
	{
		m_fontCombo->setCurrentText(family);
		m_currentFontFamily = family;
	}
}

void RibbonToolbar::setFontSize(int size)
{
	if (m_sizeCombo && m_sizeCombo->currentText().toInt() != size)
	{
		m_sizeCombo->setCurrentText(QString::number(size));
		m_currentFontSize = size;
	}
}

void RibbonToolbar::setFontColor(const QColor& color)
{
	m_currentColor = color;
	m_fontColorBtn->setIcon(createUnderlineIcon(color, ICON_SIZE));
}

void RibbonToolbar::setAlignmentState(Qt::Alignment align, bool checked)
{
	m_alignLeftBtn->setChecked(false);
	m_alignCenterBtn->setChecked(false);
	m_alignRightBtn->setChecked(false);
	m_alignJustifyBtn->setChecked(false);
	m_alignDistributedBtn->setChecked(false);
	switch (align) 
	{
	case Qt::AlignLeft:
		m_alignLeftBtn->setChecked(checked);
		break;
	case Qt::AlignCenter:
		m_alignCenterBtn->setChecked(checked);
		break;
	case Qt::AlignRight:
		m_alignRightBtn->setChecked(checked);
		break;
	case Qt::AlignJustify:
		m_alignJustifyBtn->setChecked(checked);
		break;
	case Qt::AlignJustify | Qt::AlignAbsolute:
		m_alignDistributedBtn->setChecked(checked); 
		break;
	default:
		break;
	}
}

void RibbonToolbar::onBoldClicked()
{
	m_bold = m_boldBtn->isChecked(); 
	emit boldToggled(m_bold);         
}

void RibbonToolbar::onItalicClicked()
{
	m_italic = m_italicBtn->isChecked();
	emit italicToggled(m_italic);
}

void RibbonToolbar::onUnderlineClicked()
{
	m_underline = m_underlineBtn->isChecked();
	emit underlineToggled(m_underline);
}

void RibbonToolbar::onStrikethroughClicked()
{
	m_strikethrough = m_strikethroughBtn->isChecked(); 
	emit strikethroughToggled(m_strikethrough);         
}

void RibbonToolbar::onFontFamilyChanged(int index)
{
	if (index >= 0)
	{
		QString family = m_fontCombo->itemText(index);
		m_currentFontFamily = family;
		emit fontFamilySelected(family);  
	}
}

void RibbonToolbar::onFontSizeChanged(int index)
{
	if (index >= 0)
	{
		bool ok;
		int size = m_sizeCombo->itemText(index).toInt(&ok);
		if (ok)
		{
			m_currentFontSize = size;
			emit fontSizeSelected(size);  
		}
	}
}

void RibbonToolbar::onFontSizeDecrease()
{
	int currentIndex = m_standardSizes.indexOf(m_currentFontSize);
	if (currentIndex > 0) 
	{
		int newSize = m_standardSizes[currentIndex - 1]; 
		m_sizeCombo->setCurrentText(QString::number(newSize));
		m_currentFontSize = newSize;
		emit fontSizeSelected(newSize);
	}
}

void RibbonToolbar::onFontSizeIncrease()
{
	int currentIndex = m_standardSizes.indexOf(m_currentFontSize);
	if (currentIndex != -1 && currentIndex < m_standardSizes.size() - 1) 
	{
		int newSize = m_standardSizes[currentIndex + 1]; 
		m_sizeCombo->setCurrentText(QString::number(newSize));
		m_currentFontSize = newSize;
		emit fontSizeSelected(newSize);
	}
}

void RibbonToolbar::onColorSelected(const QColor& color)
{
	m_currentColor = color;
	m_fontColorBtn->setIcon(createUnderlineIcon(color)); 
	emit fontColorSelected(color);
}


void RibbonToolbar::onInsertImageClicked()
{

	QString imagePath = QFileDialog::getOpenFileName
	(
		this,
		tr("Select an image"),
		QDir::homePath(), 
		tr("Image files (*.png *.jpg *.jpeg *.bmp *.gif);; All files (*)")
	);

	if (!imagePath.isEmpty())
		emit imageInsertRequested(imagePath); 
}

void RibbonToolbar::onInsertTableClicked()
{
	QDialog dialog(this);
	dialog.setWindowTitle(tr("Insert table"));
	dialog.setFixedSize(300, 150);

	QVBoxLayout* mainLayout = new QVBoxLayout(&dialog);
	QGridLayout* gridLayout = new QGridLayout();

	gridLayout->addWidget(new QLabel(tr("Number of lines:")), 0, 0);
	QSpinBox* rowSpin = new QSpinBox();
	rowSpin->setRange(1, 50);  
	rowSpin->setValue(3);   
	gridLayout->addWidget(rowSpin, 0, 1);


	gridLayout->addWidget(new QLabel(tr("Number of columns:")), 1, 0);
	QSpinBox* colSpin = new QSpinBox();
	colSpin->setRange(1, 20);  
	colSpin->setValue(3);      
	gridLayout->addWidget(colSpin, 1, 1);

	QHBoxLayout* btnLayout = new QHBoxLayout();
	QPushButton* okBtn = new QPushButton(tr("Sure"));
	QPushButton* cancelBtn = new QPushButton(tr("Cancel"));
	btnLayout->addWidget(okBtn);
	btnLayout->addWidget(cancelBtn);

	connect(okBtn, &QPushButton::clicked, &dialog, &QDialog::accept);
	connect(cancelBtn, &QPushButton::clicked, &dialog, &QDialog::reject);

	mainLayout->addLayout(gridLayout);
	mainLayout->addLayout(btnLayout);

	if (dialog.exec() == QDialog::Accepted) 
	{
		int rows = rowSpin->value();
		int cols = colSpin->value();
		emit tableInsertRequested(rows, cols); 
	}
}

bool RibbonToolbar::boldState() const 
{
	return m_bold; 
}

bool RibbonToolbar::italicState() const 
{
	return m_italic;  
}

bool RibbonToolbar::underlineState() const 
{
	return m_underline;  
}

QString RibbonToolbar::fontFamily() const 
{
	return m_currentFontFamily;  
}

int RibbonToolbar::fontSize() const
{
	return m_currentFontSize; 
}

void RibbonToolbar::setStrikethroughState(bool strikethrough)
{
	if (m_strikethroughBtn && m_strikethroughBtn->isChecked() != strikethrough)
	{
		m_strikethroughBtn->setChecked(strikethrough);
		m_strikethrough = strikethrough;
	}
}

bool RibbonToolbar::strikethroughState() const
{
	return m_strikethrough;
}

QColor RibbonToolbar::currentFontColor() const 
{
	return m_currentColor;
}

Qt::Alignment RibbonToolbar::currentAlignment() const
{
	if (m_alignLeftBtn->isChecked()) 
		return Qt::AlignLeft;      
	else if (m_alignCenterBtn->isChecked()) 
		return Qt::AlignCenter;    
	else if (m_alignRightBtn->isChecked()) 
		return Qt::AlignRight;     
	else if (m_alignJustifyBtn->isChecked()) 
		return Qt::AlignJustify;   
	else if (m_alignDistributedBtn->isChecked())
		return Qt::AlignJustify | Qt::AlignAbsolute; 
	return Qt::AlignLeft;
}

void RibbonToolbar::createHighlightControls(QToolBar* toolBar)
{
	m_highlightBtn = new QToolButton(toolBar);
	m_highlightBtn->setToolTip(tr("文本高亮"));
	m_highlightBtn->setIcon(createHighlightIcon(Qt::yellow));
	m_highlightBtn->setIconSize(QSize(ICON_SIZE * 2, ICON_SIZE * 2));
	m_highlightBtn->setFixedSize(BUTTON_SIZE * 2, BUTTON_SIZE);
	m_highlightBtn->setCheckable(true);

	m_highlightColorMenu = new QMenu(this);

	QWidget* colorPanel = new QWidget();
	QGridLayout* gridLayout = new QGridLayout(colorPanel);
	gridLayout->setSpacing(2); 
	gridLayout->setContentsMargins(4, 4, 4, 4);

	QVector<QColor> highlightColors = 
	{
		Qt::transparent,
		Qt::yellow,      QColor(255, 255, 153), 
		QColor(255, 204, 102), QColor(255, 153, 102), 

		QColor(255, 204, 204), QColor(255, 153, 204), 
		QColor(204, 204, 255), QColor(153, 204, 255), 

		QColor(204, 255, 204), QColor(153, 255, 153), 
		QColor(255, 255, 204), QColor(204, 255, 255), 
		QColor(255, 204, 255), QColor(204, 204, 204)  
	};

	int row = 0, col = 0;
	const int colsCount = 5; 
	for (const QColor& color : highlightColors)
	{
		QToolButton* colorBtn = new QToolButton(colorPanel);
		colorBtn->setFixedSize(24, 24);
		colorBtn->setStyleSheet("QToolButton { border: 1px solid #ccc; border-radius: 2px; }"
			"QToolButton:hover { border-color: #666; }");
		QPixmap colorPix(22, 22);
		colorPix.fill(color);
		if (color == Qt::transparent)
		{
			QPainter p(&colorPix);
			p.setPen(QPen(Qt::gray, 2, Qt::SolidLine, Qt::RoundCap));
			p.drawLine(5, 5, 17, 17);
			p.drawLine(5, 17, 17, 5);
		}
		colorBtn->setIcon(QIcon(colorPix));
		colorBtn->setIconSize(QSize(22, 22));

		connect(colorBtn, &QToolButton::clicked, this, [this, color]() 
			{
			m_highlightColor = color;
			m_highlightBtn->setIcon(createHighlightIcon(color));
			m_highlightBtn->setChecked(color != Qt::transparent);
			emit highlightColorSelected(color);
			qDebug() << color;
			});

		gridLayout->addWidget(colorBtn, row, col);

		col++;
		if (col >= colsCount) 
		{
			col = 0;
			row++;
		}
	}

	QPushButton* moreColorsBtn = new QPushButton(tr("更多颜色..."), colorPanel);
	moreColorsBtn->setStyleSheet("text-align: left; padding: 4px 8px;");
	connect(moreColorsBtn, &QPushButton::clicked, this, [this]() 
		{
		QColor color = QColorDialog::getColor(m_highlightColor, this, tr("选择高亮颜色"));
		if (color.isValid()) {
			m_highlightColor = color;
			m_highlightBtn->setIcon(createHighlightIcon(color));
			m_highlightBtn->setChecked(color != Qt::transparent);
			emit highlightColorSelected(color);
		}
		m_highlightColorMenu->close(); 
		});
	gridLayout->addWidget(moreColorsBtn, row, 0, 1, colsCount); 

	QWidgetAction* widgetAction = new QWidgetAction(m_highlightColorMenu);
	widgetAction->setDefaultWidget(colorPanel);
	m_highlightColorMenu->addAction(widgetAction);

	m_highlightBtn->setMenu(m_highlightColorMenu);
	m_highlightBtn->setPopupMode(QToolButton::MenuButtonPopup);

	connect(m_highlightBtn, &QToolButton::clicked, this, [this]() 
		{
		if (m_highlightColor == Qt::transparent) 
		{
			m_highlightColor = Qt::yellow;
			m_highlightBtn->setIcon(createHighlightIcon(Qt::yellow));
			emit highlightColorSelected(Qt::yellow);
		}
		else 
		{
			m_highlightColor = Qt::transparent;
			m_highlightBtn->setIcon(createHighlightIcon(Qt::transparent));
			m_highlightBtn->setChecked(false);
			emit highlightColorSelected(Qt::transparent);
		}
		});

	toolBar->addWidget(m_highlightBtn);
	QFrame* separator = new QFrame();
	separator->setFrameShape(QFrame::VLine);
	separator->setFrameShadow(QFrame::Sunken);
	separator->setStyleSheet("background-color: #ECECEC;");
	toolBar->addWidget(separator);
}

QPixmap RibbonToolbar::createHighlightIcon(const QColor& color, int size)
{
	QPixmap pixmap(size, size);
	pixmap.fill(Qt::transparent);

	QPainter painter(&pixmap);
	painter.setRenderHint(QPainter::Antialiasing);

	QRectF rect(1, size * 0.5, size - 2, size * 0.4);
	QBrush brush(color);
	painter.fillRect(rect, brush);

	QPainterPath path;
	path.moveTo(size * 0.2, size * 0.3);
	path.lineTo(size * 0.8, size * 0.3);
	path.lineTo(size * 0.9, size * 0.6);
	path.lineTo(size * 0.1, size * 0.6);
	path.closeSubpath();
	painter.fillPath(path, QBrush(QColor(100, 100, 100, 120)));

	if (color == Qt::transparent) 
	{
		painter.setPen(QPen(Qt::gray, 1.5, Qt::SolidLine, Qt::RoundCap));
		painter.drawLine(size * 0.2, size * 0.3, size * 0.8, size * 0.7);
		painter.drawLine(size * 0.2, size * 0.7, size * 0.8, size * 0.3);
	}

	return pixmap;
}

void RibbonToolbar::setHighlightColor(const QColor& color)
{
	m_highlightColor = color;
	m_highlightBtn->setIcon(createHighlightIcon(color));
	m_highlightBtn->setChecked(color != Qt::transparent);
}